const express = require('express');
const router = express.Router();
const authenticateToken = require('../middleware/auth');

// 获取用户收藏列表
router.get('/', authenticateToken, (req, res) => {
  const userId = req.user.userId;
  
  const query = `
    SELECT 
      f.id as favoriteId,
      f.product_id as productId,
      f.created_at as favoriteTime,
      p.title,
      p.description,
      p.price,
      p.original_price as originalPrice,
      p.image_url as imageUrl,
      p.tags
    FROM favorites f
    LEFT JOIN products p ON f.product_id = p.id
    WHERE f.user_id = ?
    ORDER BY f.created_at DESC
  `;

  global.db.query(query, [userId], (err, results) => {
    if (err) {
      console.error('获取收藏列表失败:', err);
      return res.status(500).json({ message: '获取收藏列表失败' });
    }

    const favorites = results.map(item => {
      let tags = [];
      try {
        // 安全地解析tags字段
        if (item.tags) {
          if (typeof item.tags === 'string') {
            // 如果是字符串，尝试解析为JSON
            if (item.tags.startsWith('[') && item.tags.endsWith(']')) {
              tags = JSON.parse(item.tags);
            } else {
              // 如果不是JSON格式，按逗号分割
              tags = item.tags.split(',').map(tag => tag.trim());
            }
          } else if (Array.isArray(item.tags)) {
            tags = item.tags;
          }
        }
      } catch (parseError) {
        console.warn('解析tags失败:', item.tags, parseError);
        tags = [];
      }

      return {
        id: item.productId,
        title: item.title,
        description: item.description,
        price: item.price,
        originalPrice: item.originalPrice,
        imageUrl: item.imageUrl,
        tags: tags,
        favoriteId: item.favoriteId,
        favoriteTime: item.favoriteTime
      };
    });

    res.json({
      message: '获取成功',
      favorites: favorites
    });
  });
});

// 添加收藏
router.post('/add', authenticateToken, (req, res) => {
  const userId = req.user.userId;
  const { productId } = req.body;

  if (!productId) {
    return res.status(400).json({ message: '商品ID不能为空' });
  }

  // 检查是否已收藏
  const checkQuery = 'SELECT * FROM favorites WHERE user_id = ? AND product_id = ?';
  global.db.query(checkQuery, [userId, productId], (err, results) => {
    if (err) {
      console.error('检查收藏状态失败:', err);
      return res.status(500).json({ message: '检查收藏状态失败' });
    }

    if (results.length > 0) {
      return res.status(400).json({ message: '商品已在收藏列表中' });
    }

    // 添加收藏
    const insertQuery = 'INSERT INTO favorites (user_id, product_id) VALUES (?, ?)';
    global.db.query(insertQuery, [userId, productId], (err, result) => {
      if (err) {
        console.error('添加收藏失败:', err);
        return res.status(500).json({ message: '添加收藏失败' });
      }

      res.json({ message: '收藏成功' });
    });
  });
});

// 取消收藏
router.delete('/remove/:productId', authenticateToken, (req, res) => {
  const userId = req.user.userId;
  const productId = req.params.productId;

  const deleteQuery = 'DELETE FROM favorites WHERE user_id = ? AND product_id = ?';
  global.db.query(deleteQuery, [userId, productId], (err, result) => {
    if (err) {
      console.error('取消收藏失败:', err);
      return res.status(500).json({ message: '取消收藏失败' });
    }

    if (result.affectedRows === 0) {
      return res.status(404).json({ message: '收藏记录不存在' });
    }

    res.json({ message: '取消收藏成功' });
  });
});

// 检查商品是否已收藏
router.get('/check/:productId', authenticateToken, (req, res) => {
  const userId = req.user.userId;
  const productId = req.params.productId;

  const checkQuery = 'SELECT * FROM favorites WHERE user_id = ? AND product_id = ?';
  global.db.query(checkQuery, [userId, productId], (err, results) => {
    if (err) {
      console.error('检查收藏状态失败:', err);
      return res.status(500).json({ message: '检查收藏状态失败' });
    }

    res.json({
      isCollected: results.length > 0
    });
  });
});

module.exports = router;


